from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from app.models.user import User, UserRole, UserStatus
from app.schemas.user import UserCreate, UserUpdate
from app.auth import get_password_hash


class UserService:
    def __init__(self, db: Session):
        self.db = db

    def create_user(self, user_data: UserCreate):
        """创建用户"""
        # 如果未指定角色，默认为学生
        if not user_data.role:
            user_data.role = UserRole.STUDENT
        
        # 检查用户名是否已存在
        if self.db.query(User).filter(User.username == user_data.username).first():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="用户名已存在"
            )
        
        # 检查邮箱是否已存在
        if self.db.query(User).filter(User.email == user_data.email).first():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="邮箱已存在"
            )
        
        # 检查学号是否已存在
        if user_data.student_id and self.db.query(User).filter(User.student_id == user_data.student_id).first():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="学号已存在"
            )
        
        # 创建用户
        hashed_password = get_password_hash(user_data.password)
        db_user = User(
            username=user_data.username,
            email=user_data.email,
            hashed_password=hashed_password,
            full_name=user_data.full_name,
            role=user_data.role,
            phone=user_data.phone,
            department=user_data.department,
            student_id=user_data.student_id
        )
        
        self.db.add(db_user)
        self.db.commit()
        self.db.refresh(db_user)
        
        return db_user

    def get_user(self, user_id: int):
        """获取用户信息"""
        return self.db.query(User).filter(User.id == user_id, User.is_deleted == False).first()

    def get_users(self, skip: int = 0, limit: int = 100, role: UserRole = None):
        """获取用户列表"""
        query = self.db.query(User).filter(User.is_deleted == False)
        if role:
            query = query.filter(User.role == role)
        return query.offset(skip).limit(limit).all()

    def update_user(self, user_id: int, user_data: UserUpdate):
        """更新用户信息"""
        db_user = self.get_user(user_id)
        if not db_user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 检查邮箱是否已被其他用户使用
        if user_data.email:
            existing_user = self.db.query(User).filter(
                User.email == user_data.email,
                User.id != user_id
            ).first()
            if existing_user:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="邮箱已被使用"
                )
        
        # 更新用户信息
        for field, value in user_data.dict(exclude_unset=True).items():
            setattr(db_user, field, value)
        
        self.db.commit()
        self.db.refresh(db_user)
        return db_user

    def delete_user(self, user_id: int):
        """删除用户（软删除）"""
        db_user = self.get_user(user_id)
        if not db_user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        db_user.is_deleted = True
        self.db.commit()
        return {"message": "用户删除成功"}

    def get_user_count(self, role: UserRole = None):
        """获取用户数量"""
        query = self.db.query(User).filter(User.is_deleted == False)
        if role:
            query = query.filter(User.role == role)
        return query.count()